// API 请求工具
const app = getApp()
const errorHandler = require('./error-handler')

/**
 * 发送API请求（带重试机制）
 * @param {string} url - API路径
 * @param {string} method - HTTP方法
 * @param {object} data - 请求数据
 * @param {object} options - 额外选项
 * @returns {Promise}
 */
function request(url, method = 'GET', data = {}, options = {}) {
  const {
    maxRetries = 3,
    showLoading = false,
    loadingText = '加载中...'
  } = options
  
  const token = wx.getStorageSync('access_token')
  
  return errorHandler.requestWithRetry({
    url: `${app.globalData.apiBase}${url}`,
    method: method,
    data: data,
    maxRetries: maxRetries,
    showLoadingIndicator: showLoading,
    loadingText: loadingText
  }).catch(error => {
    // Handle 401 specially
    if (error.message && error.message.includes('401')) {
      app.login()
    }
    throw error
  })
}

module.exports = {
  request,
  
  // 用户相关
  getUserProfile: () => request('/api/user/profile'),
  updateHomeLocation: (location) => request('/api/user/home-location', 'PUT', location),
  
  // 路径规划
  searchPOIs: (location, radius) => request('/api/route/search-pois', 'POST', { location, radius_meters: radius }),
  generateRoute: (data) => request('/api/route/generate', 'POST', data),
  replanRoute: (data) => request('/api/route/replan', 'POST', data),
  
  // 会话管理
  startSession: (data) => request('/api/session/start', 'POST', data),
  updateSessionLocation: (sessionId, location) => request(`/api/session/${sessionId}/location`, 'PUT', location),
  endSession: (sessionId) => request(`/api/session/${sessionId}/end`, 'POST'),
  getSessionStatus: (sessionId) => request(`/api/session/${sessionId}/status`),
  getSessionHistory: () => request('/api/session/history'),
  
  // 景点
  getPOIIntroduction: (poiId) => request(`/api/poi/${poiId}/introduction`),
  
  // 天气
  getCurrentWeather: (location) => request('/api/weather/current', 'GET', location),
  checkWeather: (location) => request('/api/weather/check', 'GET', location),
  
  // 音乐
  getMusicLibrary: () => request('/api/music/library'),
  generateMusic: (data) => request('/api/music/generate', 'POST', data),
  saveMusic: (musicId) => request(`/api/music/${musicId}/save`, 'POST'),
  deleteMusic: (musicId) => request(`/api/music/${musicId}`, 'DELETE')
}
